package com.qiwenshare.file.controller;

import cn.hutool.core.util.IdUtil;
import co.elastic.clients.elasticsearch.ElasticsearchClient;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qiwenshare.common.anno.MyLog;
import com.qiwenshare.common.exception.QiwenException;
import com.qiwenshare.common.result.RestResult;

import com.qiwenshare.common.util.DateUtil;
import com.qiwenshare.common.util.security.JwtUser;
import com.qiwenshare.common.util.security.SessionUtil;
import com.qiwenshare.file.api.IFileService;
import com.qiwenshare.file.api.IOperationLogService;
import com.qiwenshare.file.api.ITuserAccessProductService;
import com.qiwenshare.file.api.IUserFileService;
import com.qiwenshare.file.component.AsyncTaskComp;
import com.qiwenshare.file.component.FileDealComp;

import com.qiwenshare.file.domain.FileBean;
import com.qiwenshare.file.domain.OperationLogBean;
import com.qiwenshare.file.domain.UserFile;
import com.qiwenshare.file.dto.file.*;
import com.qiwenshare.file.io.QiwenFile;
import com.qiwenshare.file.mapper.FileMapper;
import com.qiwenshare.file.mapper.ImageMapper;
import com.qiwenshare.file.mapper.UserFileMapper;
import com.qiwenshare.file.util.QiwenFileUtil;
import com.qiwenshare.file.util.TreeNode;
import com.qiwenshare.file.vo.file.FileDetailVO;
import com.qiwenshare.file.vo.file.FileListVO;

import com.qiwenshare.file.vo.user.TuserAccessProductVo;
import com.qiwenshare.ufop.factory.UFOPFactory;
import com.qiwenshare.ufop.operation.copy.Copier;
import com.qiwenshare.ufop.operation.copy.domain.CopyFile;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;

@Tag(name = "file", description = "该接口为文件接口，主要用来做一些文件的基本操作，如创建目录，删除，移动，复制等。")
@RestController
@Slf4j
@RequestMapping("/file")
public class FileController {

    @Resource
    FileMapper fileMapper;
    @Resource
    ImageMapper imageMapper;

    @Resource
    UserFileMapper userFileMapper;

    @Resource
    IFileService fileService;
    @Resource
    IUserFileService userFileService;
    @Resource
    UFOPFactory ufopFactory;
    @Resource
    FileDealComp fileDealComp;

    @Resource
    ITuserAccessProductService tuserAccessProductService;
    @Resource
    IOperationLogService operationLogService;

    @Resource
    AsyncTaskComp asyncTaskComp;
    @Autowired
    private ElasticsearchClient elasticsearchClient;
    @Value("${ufop.storage-type}")
    private Integer storageType;

    public static Executor executor = Executors.newFixedThreadPool(20);

    public static final String CURRENT_MODULE = "文件接口";

    public static final String uploadType="1";//我的文件
    public static final String uploadTypeAll="2";//公共文件

    //商品系统上传下载路径
    public static final String projectPath ="D:/swq/release/static/";

    @Operation(summary = "创建文件", description = "创建文件", tags = {"file"})
    @ResponseBody
    @RequestMapping(value = "/createFile", method = RequestMethod.POST)
    public RestResult<Object> createFile(@Valid @RequestBody CreateFileDTO createFileDTO) {
        try {
            String userId = SessionUtil.getUserId();
            String filePath = createFileDTO.getFilePath();
            String fileName = createFileDTO.getFileName();
            String extendName = createFileDTO.getExtendName();
            List<UserFile> userFiles = userFileService.selectSameUserFile(fileName, filePath, extendName, userId,uploadType);
            if (userFiles != null && !userFiles.isEmpty()) {
                return RestResult.fail().message("同名文件已存在");
            }
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");

            String templateFilePath = "";
            if ("docx".equals(extendName)) {
                templateFilePath = "template/Word.docx";
            } else if ("xlsx".equals(extendName)) {
                templateFilePath = "template/Excel.xlsx";
            } else if ("pptx".equals(extendName)) {
                templateFilePath = "template/PowerPoint.pptx";
            } else if ("txt".equals(extendName)) {
                templateFilePath = "template/Text.txt";
            } else if ("drawio".equals(extendName)) {
                templateFilePath = "template/Drawio.drawio";
            }
            String url2 = ClassUtils.getDefaultClassLoader().getResource("static/" + templateFilePath).getPath();
            url2 = URLDecoder.decode(url2, "UTF-8");
            FileInputStream fileInputStream = new FileInputStream(url2);
            Copier copier = ufopFactory.getCopier();
            CopyFile copyFile = new CopyFile();
            copyFile.setExtendName(extendName);
            String fileUrl = copier.copy(fileInputStream, copyFile);

            FileBean fileBean = new FileBean();
            fileBean.setFileId(IdUtil.getSnowflakeNextIdStr());
            fileBean.setFileSize(0L);
            fileBean.setFileUrl(fileUrl);
            fileBean.setStorageType(storageType);
            fileBean.setIdentifier(uuid);
            fileBean.setCreateTime(DateUtil.getCurrentTime());
            fileBean.setCreateUserId(SessionUtil.getSession().getUserId());
            fileBean.setFileStatus(1);
            fileBean.setUploadType(uploadType);//swq231120
            boolean saveFlag = fileService.save(fileBean);
            UserFile userFile = new UserFile();
            if (saveFlag) {
                userFile.setUserFileId(IdUtil.getSnowflakeNextIdStr());
                userFile.setUserId(userId);
                userFile.setFileName(fileName);
                userFile.setFilePath(filePath);
                userFile.setDeleteFlag(0);
                userFile.setIsDir(0);
                userFile.setExtendName(extendName);
                userFile.setUploadTime(DateUtil.getCurrentTime());
                userFile.setFileId(fileBean.getFileId());
                userFile.setCreateTime(DateUtil.getCurrentTime());
                userFile.setCreateUserId(SessionUtil.getUserId());
                userFile.setUploadType(uploadType);//swq231120
                userFileService.save(userFile);
            }
            return RestResult.success().message("文件创建成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return RestResult.fail().message(e.getMessage());
        }
    }

   //SWQ231111
    @Operation(summary = "创建文件", description = "创建文件", tags = {"file"})
    @ResponseBody
    @RequestMapping(value = "/createFileAll", method = RequestMethod.POST)
    public RestResult<Object> createFileAll(@Valid @RequestBody CreateFileDTO createFileDTO) {
        try {

            String userId = SessionUtil.getUserId();
            String filePath = createFileDTO.getFilePath();
            String fileName = createFileDTO.getFileName();
            String extendName = createFileDTO.getExtendName();
            List<UserFile> userFiles = userFileService.selectSameUserFile(fileName, filePath, extendName, userId,uploadTypeAll);
            if (userFiles != null && !userFiles.isEmpty()) {
                return RestResult.fail().message("同名文件已存在");
            }
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");

            String templateFilePath = "";
            if ("docx".equals(extendName)) {
                templateFilePath = "template/Word.docx";
            } else if ("xlsx".equals(extendName)) {
                templateFilePath = "template/Excel.xlsx";
            } else if ("pptx".equals(extendName)) {
                templateFilePath = "template/PowerPoint.pptx";
            } else if ("txt".equals(extendName)) {
                templateFilePath = "template/Text.txt";
            } else if ("drawio".equals(extendName)) {
                templateFilePath = "template/Drawio.drawio";
            }
            String url2 = ClassUtils.getDefaultClassLoader().getResource("static/" + templateFilePath).getPath();
            url2 = URLDecoder.decode(url2, "UTF-8");
            FileInputStream fileInputStream = new FileInputStream(url2);
            Copier copier = ufopFactory.getCopier();
            CopyFile copyFile = new CopyFile();
            copyFile.setExtendName(extendName);
            String fileUrl = copier.copy(fileInputStream, copyFile);

            FileBean fileBean = new FileBean();
            fileBean.setFileId(IdUtil.getSnowflakeNextIdStr());
            fileBean.setFileSize(0L);
            fileBean.setFileUrl(fileUrl);
            fileBean.setStorageType(storageType);
            fileBean.setIdentifier(uuid);
            fileBean.setCreateTime(DateUtil.getCurrentTime());
            fileBean.setCreateUserId(SessionUtil.getSession().getUserId());
            fileBean.setFileStatus(1);
            fileBean.setUploadType(uploadTypeAll);//公共的
            boolean saveFlag = fileService.save(fileBean);
            UserFile userFile = new UserFile();
            if (saveFlag) {
                userFile.setUserFileId(IdUtil.getSnowflakeNextIdStr());
                userFile.setUserId(userId);
                userFile.setFileName(fileName);
                userFile.setFilePath(filePath);
                userFile.setDeleteFlag(0);
                userFile.setIsDir(0);
                userFile.setExtendName(extendName);
                userFile.setUploadTime(DateUtil.getCurrentTime());
                userFile.setFileId(fileBean.getFileId());
                userFile.setCreateTime(DateUtil.getCurrentTime());
                userFile.setCreateUserId(SessionUtil.getUserId());
                userFile.setUploadType(uploadTypeAll);//公共
                userFileService.save(userFile);
            }
            return RestResult.success().message("文件创建成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return RestResult.fail().message(e.getMessage());
        }
    }

    @Operation(summary = "创建文件夹", description = "目录(文件夹)的创建", tags = {"file"})
    @RequestMapping(value = "/createFold", method = RequestMethod.POST)
    @MyLog(operation = "创建文件夹", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult<String> createFold(@Valid @RequestBody CreateFoldDTO createFoldDto) {

        String userId = SessionUtil.getSession().getUserId();
        String filePath = createFoldDto.getFilePath();
        boolean isDirExist = fileDealComp.isDirExist(createFoldDto.getFileName(), createFoldDto.getFilePath(), userId,uploadType);
        if (isDirExist) {
            return RestResult.fail().message("同名文件夹已存在");
        }
        UserFile userFile = QiwenFileUtil.getQiwenDir(userId, filePath, createFoldDto.getFileName());
        userFile.setUploadType(uploadType);//我的文件夹
        userFileService.save(userFile);
        fileDealComp.uploadESByUserFileId(userFile.getUserFileId());
        return RestResult.success();
    }
    //SWQ231111
    @Operation(summary = "创建文件夹", description = "目录(文件夹)的创建", tags = {"file"})
    @RequestMapping(value = "/createFoldAll", method = RequestMethod.POST)
    @MyLog(operation = "创建文件夹", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult<String> createFoldAll(@Valid @RequestBody CreateFoldDTO createFoldDto) {

        String userId = SessionUtil.getSession().getUserId();
        String filePath = createFoldDto.getFilePath();
        boolean isDirExist = fileDealComp.isDirExist(createFoldDto.getFileName(), createFoldDto.getFilePath(), userId,uploadTypeAll);
        if (isDirExist) {
            return RestResult.fail().message("同名文件夹已存在");
        }
        UserFile userFile = QiwenFileUtil.getQiwenDir(userId, filePath, createFoldDto.getFileName());
        userFile.setUploadType(uploadTypeAll);//公共文件夹
        userFileService.save(userFile);
        fileDealComp.uploadESByUserFileId(userFile.getUserFileId());
        return RestResult.success();
    }

    ///SWQ231114
    @Operation(summary = "文件搜索", description = "文件搜索", tags = {"file"})
    @GetMapping(value = "/search")
    @MyLog(operation = "文件搜索", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult<FileListVO> getFileListSearch(
            @Parameter(description = "文件名称", required = true) String fileName,
           // @Parameter(description = "文件类型", required = true) String fileType,
            //@Parameter(description = "文件路径", required = true) String filePath,
            @Parameter(description = "当前页", required = true) long currentPage,
            @Parameter(description = "页面数量", required = true) long pageCount){
          //  fileType="0";
       // if ("0".equals(fileType)) {
            IPage<FileListVO> fileList = userFileService.userFileList_Search(null, fileName, currentPage, pageCount,uploadType);//上传类型 1:私人；2：公共
            return RestResult.success().dataList(fileList.getRecords(), fileList.getTotal());
     /*   } else {
            IPage<FileListVO> fileList = userFileService.getFileByFileType(Integer.valueOf(fileType), currentPage, pageCount, SessionUtil.getSession().getUserId(),"1");//上传类型 1:私人；2：公共
            return RestResult.success().dataList(fileList.getRecords(), fileList.getTotal());
        }*/
    }
/*
    public RestResult<SearchFileVO> searchFile(SearchFileDTO searchFileDTO) {
        JwtUser sessionUserBean =  SessionUtil.getSession();

        int currentPage = (int)searchFileDTO.getCurrentPage() - 1;
        int pageCount = (int)(searchFileDTO.getPageCount() == 0 ? 10 : searchFileDTO.getPageCount());

        SearchResponse<FileSearch> search = null;
        try {
            search = elasticsearchClient.search(s -> s
                            .index("filesearch")
                            .query(_1 -> _1
                                    .bool(_2 -> _2
                                            .must(_3 -> _3
                                                    .bool(_4 -> _4
                                                            .should(_5 -> _5
                                                                    .match(_6 -> _6
                                                                            .field("fileName")
                                                                            .query(searchFileDTO.getFileName())))
                                                            .should(_5 -> _5
                                                                    .wildcard(_6 -> _6
                                                                            .field("fileName")
                                                                            .wildcard("*" + searchFileDTO.getFileName() + "*")))
                                                            .should(_5 -> _5
                                                                    .match(_6 -> _6
                                                                            .field("content")
                                                                            .query(searchFileDTO.getFileName())))
                                                            .should(_5 -> _5
                                                                    .wildcard(_6 -> _6
                                                                            .field("content")
                                                                            .wildcard("*" + searchFileDTO.getFileName() + "*")))
                                                    ))
                                            .must(_3 -> _3
                                                    .term(_4 -> _4
                                                            .field("userId")
                                                            .value(sessionUserBean.getUserId())))
                                    ))
                            .from(currentPage)
                            .size(pageCount)
                            .highlight(h -> h
                                    .fields("fileName", f -> f.type("plain")
                                            .preTags("<span class='keyword'>").postTags("</span>"))
                                    .encoder(HighlighterEncoder.Html))
                            ,
                    FileSearch.class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        List<SearchFileVO> searchFileVOList = new ArrayList<>();
        for (Hit<FileSearch> hit : search.hits().hits()) {
            SearchFileVO searchFileVO = new SearchFileVO();
            BeanUtil.copyProperties(hit.source(), searchFileVO);
            searchFileVO.setHighLight(hit.highlight());
            searchFileVOList.add(searchFileVO);
            asyncTaskComp.checkESUserFileId(searchFileVO.getUserFileId());
        }
        return RestResult.success().dataList(searchFileVOList, searchFileVOList.size());
    }*/


    //SWQ231111
    @Operation(summary = "文件搜索", description = "文件搜索", tags = {"file"})
    @GetMapping(value = "/searchAll")
    @MyLog(operation = "文件搜索", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult<FileListVO> getFileListSearchAll(
            @Parameter(description = "文件名称", required = true) String fileName,
            @Parameter(description = "当前页", required = true) long currentPage,
            @Parameter(description = "页面数量", required = true) long pageCount){

        IPage<FileListVO> fileList = userFileService.userFileList_Search(null, fileName, currentPage, pageCount,uploadTypeAll);//上传类型 1:私人；2：公共
        return RestResult.success().dataList(fileList.getRecords(), fileList.getTotal());
    }

  /*  public RestResult<SearchFileVO> searchFileAll(SearchFileDTO searchFileDTO) {
        JwtUser sessionUserBean =  SessionUtil.getSession();

        int currentPage = (int)searchFileDTO.getCurrentPage() - 1;
        int pageCount = (int)(searchFileDTO.getPageCount() == 0 ? 10 : searchFileDTO.getPageCount());

        SearchResponse<FileSearch> search = null;
        try {
            search = elasticsearchClient.search(s -> s
                            .index("filesearch")
                            .query(_1 -> _1
                                    .bool(_2 -> _2
                                            .must(_3 -> _3
                                                    .bool(_4 -> _4
                                                            .should(_5 -> _5
                                                                    .match(_6 -> _6
                                                                            .field("fileName")
                                                                            .query(searchFileDTO.getFileName())))
                                                            .should(_5 -> _5
                                                                    .wildcard(_6 -> _6
                                                                            .field("fileName")
                                                                            .wildcard("*" + searchFileDTO.getFileName() + "*")))
                                                            .should(_5 -> _5
                                                                    .match(_6 -> _6
                                                                            .field("content")
                                                                            .query(searchFileDTO.getFileName())))
                                                            .should(_5 -> _5
                                                                    .wildcard(_6 -> _6
                                                                            .field("content")
                                                                            .wildcard("*" + searchFileDTO.getFileName() + "*")))
                                                    ))
                                            .must(_3 -> _3
                                                    .term(_4 -> _4
                                                            .field("userId")
                                                            .value(sessionUserBean.getUserId())))
                                    ))
                            .from(currentPage)
                            .size(pageCount)
                            .highlight(h -> h
                                    .fields("fileName", f -> f.type("plain")
                                            .preTags("<span class='keyword'>").postTags("</span>"))
                                    .encoder(HighlighterEncoder.Html))
                    ,
                    FileSearch.class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        List<SearchFileVO> searchFileVOList = new ArrayList<>();
        for (Hit<FileSearch> hit : search.hits().hits()) {
            SearchFileVO searchFileVO = new SearchFileVO();
            BeanUtil.copyProperties(hit.source(), searchFileVO);
            searchFileVO.setHighLight(hit.highlight());
            searchFileVOList.add(searchFileVO);
            asyncTaskComp.checkESUserFileId(searchFileVO.getUserFileId());
        }
        return RestResult.success().dataList(searchFileVOList, searchFileVOList.size());
    }*/

    @Operation(summary = "文件重命名", description = "文件重命名", tags = {"file"})
    @RequestMapping(value = "/renamefile", method = RequestMethod.POST)
    @MyLog(operation = "文件重命名", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult<String> renameFile(@RequestBody RenameFileDTO renameFileDto) {

        JwtUser sessionUserBean =  SessionUtil.getSession();
        UserFile userFile = userFileService.getById(renameFileDto.getUserFileId());
        //限制文件重命名
        if (userFile.getCreateUserId().equals("1")) {//管理员账号创建
            RestResult r = new RestResult();
            r.setSuccess("false".isEmpty());
            r.setCode(Integer.valueOf("500"));
            r.setMessage("此文件夹不可重命名");
            return r;
        }
        //end-限制文件重命名

        List<UserFile> userFiles = userFileService.selectUserFileByNameAndPath(renameFileDto.getFileName(), userFile.getFilePath(), sessionUserBean.getUserId(),uploadType);
        if (userFiles != null && !userFiles.isEmpty()) {
            return RestResult.fail().message("同名文件已存在");
        }

        LambdaUpdateWrapper<UserFile> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(UserFile::getFileName, renameFileDto.getFileName())
                .set(UserFile::getUploadTime, DateUtil.getCurrentTime())
                .eq(UserFile::getUserFileId, renameFileDto.getUserFileId());
        userFileService.update(lambdaUpdateWrapper);
        if (1 == userFile.getIsDir()) {
            List<UserFile> list = userFileService.selectUserFileByLikeRightFilePath(new QiwenFile(userFile.getFilePath(), userFile.getFileName(), true).getPath(), sessionUserBean.getUserId(),uploadType);

            for (UserFile newUserFile : list) {
                String escapedPattern = Pattern.quote(new QiwenFile(userFile.getFilePath(), userFile.getFileName(), userFile.getIsDir() == 1).getPath());
                newUserFile.setFilePath(newUserFile.getFilePath().replaceFirst(escapedPattern,
                        new QiwenFile(userFile.getFilePath(), renameFileDto.getFileName(), userFile.getIsDir() == 1).getPath()));
                userFileService.updateById(newUserFile);
            }
        }
        fileDealComp.uploadESByUserFileId(renameFileDto.getUserFileId());
        return RestResult.success();
    }


   //SWQ231111
    @Operation(summary = "文件重命名", description = "文件重命名", tags = {"file"})
    @RequestMapping(value = "/renamefileAll", method = RequestMethod.POST)
    @MyLog(operation = "文件重命名", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult<String> renameFileAll(@RequestBody RenameFileDTO renameFileDto) {

        JwtUser sessionUserBean =  SessionUtil.getSession();
        UserFile userFile = userFileService.getById(renameFileDto.getUserFileId());
        //限制文件重命名
        if (userFile.getCreateUserId().equals("1")) {
            RestResult r = new RestResult();
            r.setSuccess("false".isEmpty());
            r.setCode(Integer.valueOf("500"));
            r.setMessage("此文件夹不可重命名");
            return r;
        }
        //end-限制文件重命名

        List<UserFile> userFiles = userFileService.selectUserFileByNameAndPath(renameFileDto.getFileName(), userFile.getFilePath(), sessionUserBean.getUserId(),uploadTypeAll);
        if (userFiles != null && !userFiles.isEmpty()) {
            return RestResult.fail().message("同名文件已存在");
        }

        LambdaUpdateWrapper<UserFile> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(UserFile::getFileName, renameFileDto.getFileName())
                .set(UserFile::getUploadTime, DateUtil.getCurrentTime())
                .eq(UserFile::getUserFileId, renameFileDto.getUserFileId());
        userFileService.update(lambdaUpdateWrapper);
        if (1 == userFile.getIsDir()) {
            List<UserFile> list = userFileService.selectUserFileByLikeRightFilePath(new QiwenFile(userFile.getFilePath(), userFile.getFileName(), true).getPath(), sessionUserBean.getUserId(),uploadTypeAll);

            for (UserFile newUserFile : list) {
                String escapedPattern = Pattern.quote(new QiwenFile(userFile.getFilePath(), userFile.getFileName(), userFile.getIsDir() == 1).getPath());
                newUserFile.setFilePath(newUserFile.getFilePath().replaceFirst(escapedPattern,
                        new QiwenFile(userFile.getFilePath(), renameFileDto.getFileName(), userFile.getIsDir() == 1).getPath()));
                userFileService.updateById(newUserFile);
            }
        }
        fileDealComp.uploadESByUserFileId(renameFileDto.getUserFileId());
        return RestResult.success();
    }



    @Operation(summary = "获取文件列表", description = "用来做前台列表展示", tags = {"file"})
    @RequestMapping(value = "/getfilelist", method = RequestMethod.GET)
    @ResponseBody
    public RestResult<FileListVO> getFileList(
            @Parameter(description = "文件类型", required = true) String fileType,
            @Parameter(description = "文件路径", required = true) String filePath,
            @Parameter(description = "当前页", required = true) long currentPage,
            @Parameter(description = "页面数量", required = true) long pageCount){
        String isContactProduct="";//默认为空
        ///先查询是有拥有访问权限
        JwtUser sessionUserBean = SessionUtil.getSession();
        TuserAccessProductVo tuserAccessProduct=tuserAccessProductService.selectUserAccessProduct(sessionUserBean.getUserId());
        if(tuserAccessProduct!=null) isContactProduct="1"; else isContactProduct=null;
        ///end-先查询是有拥有访问权限

        if ("0".equals(fileType)) {
            //是不是包含所有个人的记录
            String isContactPrivate="";
            TuserAccessProductVo tuserAccessProductContactPri=tuserAccessProductService.selectUserAccessProductContactPrivate(sessionUserBean.getUserId());
            if(tuserAccessProductContactPri!=null) isContactPrivate="1";
            else  isContactPrivate=null;
            //是不是包含所有个人的记录

            IPage<FileListVO> fileList = userFileService.userFileList(null, filePath, currentPage, pageCount,uploadType,isContactProduct,isContactPrivate);//上传类型 1:私人；2：公共
            return RestResult.success().dataList(fileList.getRecords(), fileList.getTotal());
        } else {
            IPage<FileListVO> fileList = userFileService.getFileByFileType(Integer.valueOf(fileType), currentPage, pageCount, SessionUtil.getSession().getUserId(),uploadType);//上传类型 1:私人；2：公共
            return RestResult.success().dataList(fileList.getRecords(), fileList.getTotal());
        }
    }


    //SWQ231111
    @Operation(summary = "获取文件列表", description = "用来做前台列表展示", tags = {"file"})
    @RequestMapping(value = "/getfilelistAll", method = RequestMethod.GET)
    @ResponseBody
    public RestResult<FileListVO> getFileListAll(
            @Parameter(description = "文件类型", required = true) String fileType,
            @Parameter(description = "文件路径", required = true) String filePath,
            @Parameter(description = "当前页", required = true) long currentPage,
            @Parameter(description = "页面数量", required = true) long pageCount){

        if ("0".equals(fileType)) {
            IPage<FileListVO> fileList = userFileService.userFileList(null, filePath, currentPage, pageCount,uploadTypeAll,"","1");//上传类型 1:私人；2：公共
            return RestResult.success().dataList(fileList.getRecords(), fileList.getTotal());
        } else {
            IPage<FileListVO> fileList = userFileService.getFileByFileType(Integer.valueOf(fileType), currentPage, pageCount, SessionUtil.getSession().getUserId(),uploadTypeAll);//上传类型 1:私人；2：公共
            return RestResult.success().dataList(fileList.getRecords(), fileList.getTotal());
        }
    }


    @Operation(summary = "批量删除文件", description = "批量删除文件", tags = {"file"})
    @RequestMapping(value = "/batchdeletefile", method = RequestMethod.POST)
    @MyLog(operation = "批量删除文件", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult<String> deleteImageByIds(@RequestBody BatchDeleteFileDTO batchDeleteFileDto) {
        //String uploadType="1";//SWQ231117
        String userFileIds = batchDeleteFileDto.getUserFileIds();
        String[] userFileIdList = userFileIds.split(",");
        ////231117
        for (String userFileId : userFileIdList) {
            UserFile userFile = userFileService.getById(userFileId);
            //swq231117
            if (userFile.getCreateUserId().equals("1")) {
                RestResult r = new RestResult();
                r.setSuccess("false".isEmpty());
                r.setCode(Integer.valueOf("500"));
                r.setMessage("勾选记录包含商品系统的文件/文件夹不可删除");
                return r;
            }
            //end-swq231117
        }

        userFileService.update(new UpdateWrapper<UserFile>().lambda().set(UserFile::getDeleteFlag, 1).in(UserFile::getUserFileId, Arrays.asList(userFileIdList)));
        for (String userFileId : userFileIdList) {
            executor.execute(()->{
                    userFileService.deleteUserFile(userFileId, SessionUtil.getUserId(),uploadType);
            });
            fileDealComp.deleteESByUserFileId(userFileId);
        }
        return RestResult.success().message("批量删除文件成功");
    }

    ///SWQ231111
    @Operation(summary = "批量删除文件", description = "批量删除文件", tags = {"file"})
    @RequestMapping(value = "/batchdeletefileAll", method = RequestMethod.POST)
    @MyLog(operation = "批量删除文件", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult<String> deleteImageByIdsAll(@RequestBody BatchDeleteFileDTO batchDeleteFileDto) {
       // String uploadType="2";//SWQ231117
        String userFileIds = batchDeleteFileDto.getUserFileIds();
        String[] userFileIdList = userFileIds.split(",");
         ////231117
        for (String userFileId : userFileIdList) {
            UserFile userFile = userFileService.getById(userFileId);
            //swq231117
            if (userFile.getCreateUserId().equals("1")) {
                RestResult r = new RestResult();
                r.setSuccess("false".isEmpty());
                r.setCode(Integer.valueOf("500"));
                r.setMessage("勾选记录包含商品系统的文件/文件夹不可删除");
                return r;
            }
            //end-swq231117
        }


        userFileService.update(new UpdateWrapper<UserFile>().lambda().set(UserFile::getDeleteFlag, 1).in(UserFile::getUserFileId, Arrays.asList(userFileIdList)));
        for (String userFileId : userFileIdList) {
            executor.execute(()->{
                userFileService.deleteUserFile(userFileId, SessionUtil.getUserId(),uploadTypeAll);
            });
            fileDealComp.deleteESByUserFileId(userFileId);
        }
        return RestResult.success().message("批量删除文件成功");
    }



    @Operation(summary = "删除文件", description = "可以删除文件或者目录", tags = {"file"})
    @RequestMapping(value = "/deletefile", method = RequestMethod.POST)
    @MyLog(operation = "删除文件", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult deleteFile(@RequestBody DeleteFileDTO deleteFileDto) {
        UserFile userFile=userFileService.selectUserFileByUserFileId(deleteFileDto.getUserFileId());
        if(userFile!=null) {
            if (!userFile.getCreateUserId().equals("1")) {
              //  String uploadType = "1";//我的文件删除
                JwtUser sessionUserBean = SessionUtil.getSession();
                userFileService.deleteUserFile(deleteFileDto.getUserFileId(), sessionUserBean.getUserId(), uploadType);
                fileDealComp.deleteESByUserFileId(deleteFileDto.getUserFileId());
                return RestResult.success();
            }
        else {

                    RestResult r = new RestResult();
                    r.setSuccess("false".isEmpty());
                    r.setCode(Integer.valueOf("500"));
                    r.setMessage("此文件/文件夹不可删除");
                    return r;
                }
            }
            else
                return RestResult.fail();
    }

    //swq231111
    @Operation(summary = "删除文件", description = "可以删除文件或者目录", tags = {"file"})
    @RequestMapping(value = "/deletefileAll", method = RequestMethod.POST)
    @MyLog(operation = "删除文件", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult deleteFileAll(@RequestBody DeleteFileDTO deleteFileDto) {
        UserFile userFile=userFileService.selectUserFileByUserFileId(deleteFileDto.getUserFileId());
        if(userFile!=null) {
            if (!userFile.getCreateUserId().equals("1")) {
                //String uploadType = "2";//公共文件删除
                JwtUser sessionUserBean = SessionUtil.getSession();
                userFileService.deleteUserFile(deleteFileDto.getUserFileId(), sessionUserBean.getUserId(), uploadTypeAll);
                fileDealComp.deleteESByUserFileId(deleteFileDto.getUserFileId());
                return RestResult.success();
            } else {

                RestResult r = new RestResult();
                r.setSuccess("false".isEmpty());
                r.setCode(Integer.valueOf("500"));
                r.setMessage("此文件/文件夹不可删除");
                return r;
            }
        }
        else
            return RestResult.fail();
    }

    @Operation(summary = "解压文件", description = "解压文件。", tags = {"file"})
    @RequestMapping(value = "/unzipfile", method = RequestMethod.POST)
    @MyLog(operation = "解压文件", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult<String> unzipFile(@RequestBody UnzipFileDTO unzipFileDto) {
        try {
            fileService.unzipFile(unzipFileDto.getUserFileId(), unzipFileDto.getUnzipMode(), unzipFileDto.getFilePath(),uploadType);
        } catch (QiwenException e) {
            return RestResult.fail().message(e.getMessage());
        }
        return RestResult.success();
    }

    //swq231111
    @Operation(summary = "解压文件", description = "解压文件。", tags = {"file"})
    @RequestMapping(value = "/unzipfileAll", method = RequestMethod.POST)
    @MyLog(operation = "解压文件", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult<String> unzipFileAll(@RequestBody UnzipFileDTO unzipFileDto) {

        try {
            fileService.unzipFile(unzipFileDto.getUserFileId(), unzipFileDto.getUnzipMode(), unzipFileDto.getFilePath(),uploadTypeAll);
        } catch (QiwenException e) {
            return RestResult.fail().message(e.getMessage());
        }
        return RestResult.success();
    }

    @Operation(summary = "文件复制", description = "可以复制文件或者目录", tags = {"file"})
    @RequestMapping(value = "/copyfile", method = RequestMethod.POST)
    @MyLog(operation = "文件复制", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult<String> copyFile(@RequestBody CopyFileDTO copyFileDTO) {
        String userId = SessionUtil.getUserId();
        String filePath = copyFileDTO.getFilePath();
        String userFileIds = copyFileDTO.getUserFileIds();
        String[] userFileIdArr = userFileIds.split(",");
        for (String userFileId : userFileIdArr) {
            UserFile userFile = userFileService.getById(userFileId);
            String oldfilePath = userFile.getFilePath();
            String fileName = userFile.getFileName();
            if (userFile.isDirectory()) {
                QiwenFile qiwenFile = new QiwenFile(oldfilePath, fileName, true);
                if (filePath.startsWith(qiwenFile.getPath() + QiwenFile.separator) || filePath.equals(qiwenFile.getPath())) {
                    return RestResult.fail().message("原路径与目标路径冲突，不能复制");
                }
            }
            userFileService.userFileCopy(SessionUtil.getUserId(), userFileId, filePath,uploadType);
            fileDealComp.deleteRepeatSubDirFile(filePath, userId);
        }
        return RestResult.success();
    }


  //swq231111
    @Operation(summary = "文件复制", description = "可以复制文件或者目录", tags = {"file"})
    @RequestMapping(value = "/copyfileAll", method = RequestMethod.POST)
    @MyLog(operation = "文件复制", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult<String> copyFileAll(@RequestBody CopyFileDTO copyFileDTO) {
        String userId = SessionUtil.getUserId();
        String filePath = copyFileDTO.getFilePath();
        String userFileIds = copyFileDTO.getUserFileIds();
        String[] userFileIdArr = userFileIds.split(",");
        for (String userFileId : userFileIdArr) {
            UserFile userFile = userFileService.getById(userFileId);
            String oldfilePath = userFile.getFilePath();
            String fileName = userFile.getFileName();
            if (userFile.isDirectory()) {
                QiwenFile qiwenFile = new QiwenFile(oldfilePath, fileName, true);
                if (filePath.startsWith(qiwenFile.getPath() + QiwenFile.separator) || filePath.equals(qiwenFile.getPath())) {
                    return RestResult.fail().message("原路径与目标路径冲突，不能复制");
                }
            }
            userFileService.userFileCopy(SessionUtil.getUserId(), userFileId, filePath,uploadTypeAll);
            fileDealComp.deleteRepeatSubDirFile(filePath, userId);
        }
        return RestResult.success();
    }


    @Operation(summary = "文件移动", description = "可以移动文件或者目录", tags = {"file"})
    @RequestMapping(value = "/movefile", method = RequestMethod.POST)
    @MyLog(operation = "文件移动", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult<String> moveFile(@RequestBody MoveFileDTO moveFileDto) {

        JwtUser sessionUserBean =  SessionUtil.getSession();
        UserFile userFile = userFileService.getById(moveFileDto.getUserFileId());
        //swq231117
        if (userFile.getCreateUserId().equals("1")) {
            RestResult r = new RestResult();
            r.setSuccess("false".isEmpty());
            r.setCode(Integer.valueOf("500"));
            r.setMessage("此文件/文件夹不可移动");
            return r;
        }
        //end-swq231117

        String oldfilePath = userFile.getFilePath();
        String newfilePath = moveFileDto.getFilePath();
        String fileName = userFile.getFileName();
        String extendName = userFile.getExtendName();
        if (StringUtil.isEmpty(extendName)) {
            QiwenFile qiwenFile = new QiwenFile(oldfilePath, fileName, true);
            if (newfilePath.startsWith(qiwenFile.getPath() + QiwenFile.separator) || newfilePath.equals(qiwenFile.getPath())) {
                return RestResult.fail().message("原路径与目标路径冲突，不能移动");
            }
        }
        userFileService.updateFilepathByUserFileId(moveFileDto.getUserFileId(), newfilePath, sessionUserBean.getUserId());
        fileDealComp.deleteRepeatSubDirFile(newfilePath, sessionUserBean.getUserId());
        return RestResult.success();
    }


    //swq231111
    @Operation(summary = "文件移动", description = "可以移动文件或者目录", tags = {"file"})
    @RequestMapping(value = "/movefileAll", method = RequestMethod.POST)
    @MyLog(operation = "文件移动", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult<String> moveFileAll(@RequestBody MoveFileDTO moveFileDto) {

        JwtUser sessionUserBean =  SessionUtil.getSession();
        UserFile userFile = userFileService.getById(moveFileDto.getUserFileId());
        //swq231117
        if (userFile.getCreateUserId().equals("1")) {
            RestResult r = new RestResult();
            r.setSuccess("false".isEmpty());
            r.setCode(Integer.valueOf("500"));
            r.setMessage("此文件/文件夹不可移动");
            return r;
        }
        //end-swq231117

        String oldfilePath = userFile.getFilePath();
        String newfilePath = moveFileDto.getFilePath();
        String fileName = userFile.getFileName();
        String extendName = userFile.getExtendName();
        if (StringUtil.isEmpty(extendName)) {
            QiwenFile qiwenFile = new QiwenFile(oldfilePath, fileName, true);
            if (newfilePath.startsWith(qiwenFile.getPath() + QiwenFile.separator) || newfilePath.equals(qiwenFile.getPath())) {
                return RestResult.fail().message("原路径与目标路径冲突，不能移动");
            }
        }
        userFileService.updateFilepathByUserFileId(moveFileDto.getUserFileId(), newfilePath, sessionUserBean.getUserId());
        fileDealComp.deleteRepeatSubDirFile(newfilePath, sessionUserBean.getUserId());
        return RestResult.success();
    }

    @Operation(summary = "批量移动文件", description = "可以同时选择移动多个文件或者目录", tags = {"file"})
    @RequestMapping(value = "/batchmovefile", method = RequestMethod.POST)
    @MyLog(operation = "批量移动文件", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult<String> batchMoveFile(@RequestBody BatchMoveFileDTO batchMoveFileDto) {

        JwtUser sessionUserBean =  SessionUtil.getSession();
        String newfilePath = batchMoveFileDto.getFilePath();
        String userFileIds = batchMoveFileDto.getUserFileIds();
        String[] userFileIdArr = userFileIds.split(",");
        for (String userFileId : userFileIdArr) {
            UserFile userFile = userFileService.getById(userFileId);
            //swq231117
            if (userFile.getCreateUserId().equals("1")) {
                RestResult r = new RestResult();
                r.setSuccess("false".isEmpty());
                r.setCode(Integer.valueOf("500"));
                r.setMessage("勾选记录包含商品系统的文件/文件夹不可移动");
                return r;
            }
            //end-swq231117
        }

        for (String userFileId : userFileIdArr) {
            UserFile userFile = userFileService.getById(userFileId);
            if (StringUtil.isEmpty(userFile.getExtendName())) {
                QiwenFile qiwenFile = new QiwenFile(userFile.getFilePath(), userFile.getFileName(), true);
                if (newfilePath.startsWith(qiwenFile.getPath() + QiwenFile.separator) || newfilePath.equals(qiwenFile.getPath())) {
                    return RestResult.fail().message("原路径与目标路径冲突，不能移动");
                }
            }
            userFileService.updateFilepathByUserFileId(userFile.getUserFileId(), newfilePath, sessionUserBean.getUserId());
        }
        return RestResult.success().data("批量移动文件成功");
    }

    //swq231111
    @Operation(summary = "批量移动文件", description = "可以同时选择移动多个文件或者目录", tags = {"file"})
    @RequestMapping(value = "/batchmovefileAll", method = RequestMethod.POST)
    @MyLog(operation = "批量移动文件", module = CURRENT_MODULE)
    @ResponseBody
    public RestResult<String> batchMoveFileAll(@RequestBody BatchMoveFileDTO batchMoveFileDto) {
        JwtUser sessionUserBean =  SessionUtil.getSession();
        String newfilePath = batchMoveFileDto.getFilePath();
        String userFileIds = batchMoveFileDto.getUserFileIds();
        String[] userFileIdArr = userFileIds.split(",");
        for (String userFileId : userFileIdArr) {
            UserFile userFile = userFileService.getById(userFileId);
            //swq231117
            if (userFile.getCreateUserId().equals("1")) {
                RestResult r = new RestResult();
                r.setSuccess("false".isEmpty());
                r.setCode(Integer.valueOf("500"));
                r.setMessage("勾选记录包含商品系统的文件/文件夹不可移动");
                return r;
            }
            //end-swq231117
        }

        for (String userFileId : userFileIdArr) {
            UserFile userFile = userFileService.getById(userFileId);
            if (StringUtil.isEmpty(userFile.getExtendName())) {
                QiwenFile qiwenFile = new QiwenFile(userFile.getFilePath(), userFile.getFileName(), true);
                if (newfilePath.startsWith(qiwenFile.getPath() + QiwenFile.separator) || newfilePath.equals(qiwenFile.getPath())) {
                    return RestResult.fail().message("原路径与目标路径冲突，不能移动");
                }
            }
            userFileService.updateFilepathByUserFileId(userFile.getUserFileId(), newfilePath, sessionUserBean.getUserId());
        }
        return RestResult.success().data("批量移动文件成功");
    }

    @Operation(summary = "获取文件树", description = "文件移动的时候需要用到该接口，用来展示目录树", tags = {"file"})
    @RequestMapping(value = "/getfiletree", method = RequestMethod.GET)
    @ResponseBody
    public RestResult<TreeNode> getFileTree() {
        RestResult<TreeNode> result = new RestResult<TreeNode>();

        JwtUser sessionUserBean =  SessionUtil.getSession();
        List<UserFile> userFileList = userFileService.selectFilePathTreeByUserId(sessionUserBean.getUserId(),uploadType);
        TreeNode resultTreeNode = new TreeNode();
        resultTreeNode.setLabel(QiwenFile.separator);
        resultTreeNode.setId(0L);
        long id = 1;
        for (int i = 0; i < userFileList.size(); i++){
            UserFile userFile = userFileList.get(i);
            QiwenFile qiwenFile = new QiwenFile(userFile.getFilePath(), userFile.getFileName(), false);
            String filePath = qiwenFile.getPath();

            Queue<String> queue = new LinkedList<>();

            String[] strArr = filePath.split(QiwenFile.separator);
            for (int j = 0; j < strArr.length; j++){
                if (!"".equals(strArr[j]) && strArr[j] != null){
                    queue.add(strArr[j]);
                }

            }
            if (queue.size() == 0){
                continue;
            }
            resultTreeNode = fileDealComp.insertTreeNode(resultTreeNode, id++, QiwenFile.separator, queue);
        }
        List<TreeNode> treeNodeList = resultTreeNode.getChildren();
        Collections.sort(treeNodeList, (o1, o2) -> {
            long i = o1.getId() - o2.getId();
            return (int) i;
        });
        result.setSuccess(true);
        result.setData(resultTreeNode);
        return result;

    }

   //swq231111
    @Operation(summary = "获取文件树", description = "文件移动的时候需要用到该接口，用来展示目录树", tags = {"file"})
    @RequestMapping(value = "/getfiletreeAll", method = RequestMethod.GET)
    @ResponseBody
    public RestResult<TreeNode> getFileTreeAll() {
        RestResult<TreeNode> result = new RestResult<TreeNode>();

        JwtUser sessionUserBean =  SessionUtil.getSession();

        List<UserFile> userFileList = userFileService.selectFilePathTreeByUserId(sessionUserBean.getUserId(),uploadTypeAll);
        TreeNode resultTreeNode = new TreeNode();
        resultTreeNode.setLabel(QiwenFile.separator);
        resultTreeNode.setId(0L);
        long id = 1;
        for (int i = 0; i < userFileList.size(); i++){
            UserFile userFile = userFileList.get(i);
            QiwenFile qiwenFile = new QiwenFile(userFile.getFilePath(), userFile.getFileName(), false);
            String filePath = qiwenFile.getPath();

            Queue<String> queue = new LinkedList<>();

            String[] strArr = filePath.split(QiwenFile.separator);
            for (int j = 0; j < strArr.length; j++){
                if (!"".equals(strArr[j]) && strArr[j] != null){
                    queue.add(strArr[j]);
                }

            }
            if (queue.size() == 0){
                continue;
            }

            resultTreeNode = fileDealComp.insertTreeNode(resultTreeNode, id++, QiwenFile.separator, queue);


        }
        List<TreeNode> treeNodeList = resultTreeNode.getChildren();
        Collections.sort(treeNodeList, (o1, o2) -> {
            long i = o1.getId() - o2.getId();
            return (int) i;
        });
        result.setSuccess(true);
        result.setData(resultTreeNode);
        return result;

    }



    @Operation(summary = "修改文件", description = "支持普通文本类文件的修改", tags = {"file"})
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public RestResult<String> updateFile(@RequestBody UpdateFileDTO updateFileDTO) {
        JwtUser sessionUserBean =  SessionUtil.getSession();
        UserFile userFile = userFileService.getById(updateFileDTO.getUserFileId());
        FileBean fileBean = fileService.getById(userFile.getFileId());
        Long pointCount = fileService.getFilePointCount(userFile.getFileId());
        String fileUrl = fileBean.getFileUrl();
        if (pointCount > 1) {
            fileUrl = fileDealComp.copyFile(fileBean, userFile);
        }
        String content = updateFileDTO.getFileContent();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(content.getBytes());
        try {
            int fileSize = byteArrayInputStream.available();
            fileDealComp.saveFileInputStream(fileBean.getStorageType(), fileUrl, byteArrayInputStream);

            String md5Str = fileDealComp.getIdentifierByFile(fileUrl, fileBean.getStorageType());

            fileService.updateFileDetail(userFile.getUserFileId(), md5Str, fileSize);


        } catch (Exception e) {
            throw new QiwenException(999999, "修改文件异常");
        } finally {
            try {
                byteArrayInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return RestResult.success().message("修改文件成功");
    }


    //SWQ231111
    @Operation(summary = "修改文件", description = "支持普通文本类文件的修改", tags = {"file"})
    @RequestMapping(value = "/updateAll", method = RequestMethod.POST)
    @ResponseBody
    public RestResult<String> updateFileAll(@RequestBody UpdateFileDTO updateFileDTO) {
        JwtUser sessionUserBean =  SessionUtil.getSession();
        UserFile userFile = userFileService.getById(updateFileDTO.getUserFileId());
        FileBean fileBean = fileService.getById(userFile.getFileId());
        Long pointCount = fileService.getFilePointCount(userFile.getFileId());
        String fileUrl = fileBean.getFileUrl();
        if (pointCount > 1) {
            fileUrl = fileDealComp.copyFile(fileBean, userFile);
        }
        String content = updateFileDTO.getFileContent();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(content.getBytes());
        try {
            int fileSize = byteArrayInputStream.available();
            fileDealComp.saveFileInputStream(fileBean.getStorageType(), fileUrl, byteArrayInputStream);

            String md5Str = fileDealComp.getIdentifierByFile(fileUrl, fileBean.getStorageType());

            fileService.updateFileDetail(userFile.getUserFileId(), md5Str, fileSize);


        } catch (Exception e) {
            throw new QiwenException(999999, "修改文件异常");
        } finally {
            try {
                byteArrayInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return RestResult.success().message("修改文件成功");
    }


    @Operation(summary = "查询文件详情", description = "查询文件详情", tags = {"file"})
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    @ResponseBody
    public RestResult<FileDetailVO> queryFileDetail(
            @Parameter(description = "用户文件Id", required = true) String userFileId){
        FileDetailVO vo = fileService.getFileDetail(userFileId);
        return RestResult.success().data(vo);
    }

    //swq231111
    @Operation(summary = "查询文件详情", description = "查询文件详情", tags = {"file"})
    @RequestMapping(value = "/detailAll", method = RequestMethod.GET)
    @ResponseBody
    public RestResult<FileDetailVO> queryFileDetailAll(
            @Parameter(description = "用户文件Id", required = true) String userFileId){
        FileDetailVO vo = fileService.getFileDetail(userFileId);
        return RestResult.success().data(vo);
    }




///////////////////swq231123.1 商品系统-删除
@Operation(summary = "批量删除文件-商品", description = "批量删除文件-商品", tags = {"file"})
@RequestMapping(value = "/batchdeletefileProduct", method = RequestMethod.DELETE)
@MyLog(operation = "批量删除文件-商品", module = CURRENT_MODULE)
public    Map<String,Object>  batchdeletefileProduct(HttpServletRequest request, HttpServletResponse response) throws IOException {
       String userFileIds = request.getParameter("userFileIds");
       String userId= request.getParameter("userId");//用户钉钉通知
       String id= request.getParameter("id");//商品记录ID
       Map<String,Object> jsonObject = new HashMap<String, Object>(); //创建Json对象
       String flag="";//响应返回值
       String delNum="0";//返回删除记录数
        try {
            int  delNumSuc=0,delNumFail=0;
            String[] userFileIdList = userFileIds.split(",");
               ////swq20240119 先判断要删除的个数有没有超过60个文件
                System.out.println("已选删除个数为:"+userFileIdList.length);
                 if(userFileIdList.length>60)
                 {
                     jsonObject.put("flag",false);
                     jsonObject.put("msg","一次删除文件个数不能超过60,已选个数:"+userFileIdList.length);
                     return  jsonObject;
                 }
               ////end-20240119先判断要删除的个数有没有超过60个文件

            userFileService.update(new UpdateWrapper<UserFile>().lambda().set(UserFile::getDeleteFlag, 1).in(UserFile::getUserFileId, Arrays.asList(userFileIdList)));
            for (String userFileId : userFileIdList) {
                ////逐一删除
                FileBean fileBean=fileMapper.selectFileOnlyRecord(userFileId);
                if(fileBean!=null) {
                    String projectPath1= projectPath+fileBean.getFileUrl();
                    File file = new File(projectPath1);
                    if (file.delete()) {
                        System.out.println("文件删除成功！");
                        int num1=userFileMapper.deleteByFileId(userFileId);//删除记录
                        int num2=imageMapper.deleteByFileId(userFileId);
                        int num3=fileMapper.deleteByFileId(userFileId);
                        System.out.println(num1+","+num2+","+num3);
                        delNumSuc=delNumSuc+1;
                    } else {
                        delNumFail=delNumFail+1;
                        System.out.println("文件删除失败！");
                    }
                }
                ////逐一删除
            }

            if(delNumSuc>0) //有删除数据
            {
                JSONObject jsobj1 = new JSONObject();
                jsobj1.put("userFileIds", userFileIds);
                jsobj1.put("userId", userId);
                jsobj1.put("id", id);
                 String returnStr = post(jsobj1, "http://110.81.207.46:8081/upload/deleteFile");
                 //String returnStr = post(jsobj1, "http://127.0.0.1:8081/upload/deleteFile");
                Map<String, Object> map = json2Map(returnStr.toString());
                flag = map.get("flag").toString();
                delNum = map.get("delNum").toString();
                String msg=map.get("msg").toString();
                if(flag.equals("true")) {//返回插入数据成功,给前端返回结果
                    ///swq231201写入操作日志
                    String ipAddress = request.getRemoteAddr();
                    OperationLogBean operationlogBean=new OperationLogBean();
                    operationlogBean.setDetail("删除文件:"+userFileIdList.length+"个数");
                    operationlogBean.setOperation("文件删除");
                    operationlogBean.setRequestMethod("Get");
                    operationlogBean.setRequestURI("/file/batchdeletefileProduct");
                    operationlogBean.setResult("成功删除:"+delNumSuc+"个,失败:"+delNumFail);
                    operationlogBean.setTerminal(ipAddress);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date currentDate = new Date();
                    String formattedDate = sdf.format(currentDate);
                    operationlogBean.setTime(formattedDate);
                    operationlogBean.setUserId("商品系统用户主动删除");
                    operationlogBean.setSource("文件批量删除接口");
                    operationLogService.insertOperationLog(operationlogBean);
                    ///swq231201-写入操作日志
                    //响应
                    jsonObject.put("flag",true);     //设置Json对象的属性
                    if(delNumFail==0)
                    jsonObject.put("msg","成功删除:"+delNumSuc+"个文件");
                    else
                    jsonObject.put("msg","成功删除:"+delNumSuc+"个,失败:"+delNumFail);
                    return jsonObject;
                }
                else{
                    jsonObject.put("flag",false);     //设置Json对象的属性
                    jsonObject.put("msg","返回信息:"+msg);
                    return jsonObject;
                }
            }
            else {
                jsonObject.put("flag",false);     //设置Json对象的属性
                jsonObject.put("msg","没有找到要删除的记录.");
                return jsonObject;
            }
        }
        catch (Exception e)
        {
            ///swq231129写入操作日志
            String ipAddress = request.getRemoteAddr();
            OperationLogBean operationlogBean=new OperationLogBean();
            operationlogBean.setDetail("删除文件ID:"+userFileIds);
            operationlogBean.setOperation("文件删除");
            operationlogBean.setRequestMethod("Get");
            operationlogBean.setRequestURI("/file/batchdeletefileProduct");
            operationlogBean.setResult("失败:"+e.getMessage());
            operationlogBean.setTerminal(ipAddress);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date currentDate = new Date();
            String formattedDate = sdf.format(currentDate);
            operationlogBean.setTime(formattedDate);
            operationlogBean.setUserId("商品系统用户主动删除");
            operationlogBean.setSource("文件批量删除接口");
            operationLogService.insertOperationLog(operationlogBean);
            ///end-写入操作日志
            jsonObject.put("flag",false);     //设置Json对象的属性
            jsonObject.put("msg","异常信息:"+e.getMessage());
        }
    return jsonObject;
}


    ////swq20240403-001促销模块-删除图片
    @Operation(summary = "删除文件-促销", description = "删除文件-促销", tags = {"file"})
    @RequestMapping(value = "/batchDeleteFilePromotion", method = RequestMethod.DELETE)
    @MyLog(operation = "批量删除文件-商品", module = CURRENT_MODULE)
    public    Map<String,Object>  batchDeleteFilePromotion(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String userFileIds = request.getParameter("userFileIds");
        Map<String, Object> jsonObject = new HashMap<String, Object>(); //创建Json对象
        try {
            int delNumSuc = 0, delNumFail = 0;
            String[] userFileIdList = userFileIds.split(",");
            ////swq20240119 先判断要删除的个数有没有超过60个文件
            System.out.println("已选删除个数为:" + userFileIdList.length);
            if (userFileIdList.length > 60) {
                jsonObject.put("code", 500);
                jsonObject.put("msg", "一次删除文件个数不能超过60,已选个数:" + userFileIdList.length);
                return jsonObject;
            }
            ////end-20240119先判断要删除的个数有没有超过60个文件

            userFileService.update(new UpdateWrapper<UserFile>().lambda().set(UserFile::getDeleteFlag, 1).in(UserFile::getUserFileId, Arrays.asList(userFileIdList)));
            for (String userFileId : userFileIdList) {
                ////逐一删除
                FileBean fileBean = fileMapper.selectFileOnlyRecord(userFileId);
                if (fileBean != null) {
                    String projectPath1 = projectPath + fileBean.getFileUrl();
                    File file = new File(projectPath1);
                    if (file.delete()) {
                        System.out.println("文件删除成功！");
                        int num1 = userFileMapper.deleteByFileId(userFileId);//删除记录
                        int num2 = imageMapper.deleteByFileId(userFileId);
                        int num3 = fileMapper.deleteByFileId(userFileId);
                        System.out.println(num1 + "," + num2 + "," + num3);
                        delNumSuc = delNumSuc + 1;
                    } else {
                        delNumFail = delNumFail + 1;
                        System.out.println("文件删除失败！");
                    }
                }
                ////逐一删除
            }
            jsonObject.put("code", 200);
            jsonObject.put("msg", "成功删除" + delNumSuc + "文件");
            return jsonObject;
        } catch (Exception  e)
        {
            jsonObject.put("code", 500);
            jsonObject.put("msg", "文件删除失败" +e.getMessage());
            return jsonObject;
        }

    }



    //02.等待01调用
    public static String post(JSONObject json,String url) {
        String result="";
        try {
            HttpClient client=new DefaultHttpClient();
            HttpPost post=new HttpPost(url);
            post.setHeader("Content-Type", "appliction/json");
            post.addHeader("Authorization", "Basic YWRtaW46");
            StringEntity s=new StringEntity(json.toString(), "utf-8");
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "appliction/json"));
            post.setEntity(s);
            HttpResponse httpResponse=client.execute(post);
            InputStream in=httpResponse.getEntity().getContent();
            BufferedReader br=new BufferedReader(new InputStreamReader(in, "utf-8"));
            StringBuilder strber=new StringBuilder();
            String line=null;
            while ((line=br.readLine())!=null) {
                strber.append(line+"\n");
            }
            in.close();
            result=strber.toString();
            if(httpResponse.getStatusLine().getStatusCode()!= HttpStatus.SC_OK){
                result="服务器异常";
            }
        } catch (Exception e) {
            System.out.println("请求异常");
            throw new RuntimeException(e);
        }
        System.out.println("result=="+result);
        return result;
    }
   //03.被01调用
    public static Map<String, Object> json2Map(String jsonStr) {
        Map<String, Object> map = new HashMap<>();
        if(jsonStr != null && !"".equals(jsonStr)){
            //最外层解析
            JSONObject json = JSONObject.parseObject(jsonStr);
            for (Object k : json.keySet()) {
                Object v = json.get(k);
                //如果内层还是数组的话，继续解析
                if (v instanceof JSONArray) {
                    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                    Iterator<Object> it = ((JSONArray) v).iterator();
                    while (it.hasNext()) {
                        JSONObject json2 = (JSONObject) it.next();
                        list.add(json2Map(json2.toString()));
                    }
                    map.put(k.toString(), list);
                } else {
                    map.put(k.toString(), v);
                }
            }
            return map;
        }else{
            return null;
        }
    }

}
